import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/services.dart';

extension StringExtension on String {
  int? toIntOrNull() {
    return int.tryParse(this);
  }

  double? toDoubleOrNull() {
    return double.tryParse(this);
  }

  num? toNumOrNull() {
    return num.tryParse(this);
  }

  ///设置文本到剪切板
  Future<void> setData() {
    String text = this;
    return Clipboard.setData(ClipboardData(text: text));
  }

  String ifEmpty(String Function() function) {
    String value = this;
    if (value.isEmpty) return value;
    return function();
  }

  ///过滤Emoji
  String filterEmoji() {
    String content = this;
    RegExp regexp = RegExp("[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]");
    return content.replaceAll(regexp, "");
  }

  ///是否包含Emoji
  bool containsEmoji() {
    String content = this;
    RegExp regexp = RegExp("[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]");
    return content.contains(regexp);
  }

  String generateMd5() {
    var content = const Utf8Encoder().convert(this);
    var digest = md5.convert(content);
    return digest.toString();
  }

  /// 转暗文 星号
  String toCiphertext() {
    return replaceAll(RegExp(r"[\s\S]"), "*");
  }

  ///隐藏手机号
  String hideMobile() {
    String mobile = this;
    if (11 == mobile.length) {
      return "${mobile.substring(0, 3)}****${mobile.substring(mobile.length - 4, mobile.length)}";
    }
    return mobile;
  }

}
